package com.ruoyi.smart.service;

import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.core.redis.RedisSetCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class DeviceStatusService {

    // Redis key前缀
    private static final String DEVICE_STATUS_KEY = "smart:device:status:";
    private static final String DEVICE_LAST_ACTIVE_KEY = "smart:device:lastActive:";
    private static final String ALL_DEVICES_KEY = "smart:device:all";

    @Resource
    private RedisCache redisCache;
    @Resource
    private RedisSetCache redisSetCache;
    /**
     * 更新设备状态
     */
    public void updateDeviceStatus(String deviceId, boolean online) {
        // 更新设备状态
        redisCache.setCacheObject(DEVICE_STATUS_KEY + deviceId, online, 30, TimeUnit.DAYS);

        // 更新最后活动时间
        redisCache.setCacheObject(DEVICE_LAST_ACTIVE_KEY + deviceId, System.currentTimeMillis(), 30, TimeUnit.DAYS);

        // 添加到所有设备集合 - 使用扩展的 RedisSetCache
        redisSetCache.addSetValue(ALL_DEVICES_KEY, deviceId);

        log.info("设备 {} 状态更新为: {}", deviceId, online ? "在线" : "离线");
    }

    /**
     * 获取设备状态
     */
    public Boolean getDeviceStatus(String deviceId) {
        return redisCache.getCacheObject(DEVICE_STATUS_KEY + deviceId);
    }

    /**
     * 获取所有设备状态
     */
    public Map<String, Boolean> getAllDeviceStatus() {
        Set<Object> deviceIds = redisSetCache.getSet(ALL_DEVICES_KEY);
        Map<String, Boolean> result = new HashMap<>();

        if (deviceIds != null) {
            for (Object deviceIdObj : deviceIds) {
                String deviceId = (String) deviceIdObj;
                Boolean status = getDeviceStatus(deviceId);
                if (status != null) {
                    result.put(deviceId, status);
                }
            }
        }

        return result;
    }

    /**
     * 获取设备最后活动时间
     */
    public Long getDeviceLastActive(String deviceId) {
        return redisCache.getCacheObject(DEVICE_LAST_ACTIVE_KEY + deviceId);
    }

    /**
     * 移除设备状态信息
     */
    public void removeDevice(String deviceId) {
        redisCache.deleteObject(DEVICE_STATUS_KEY + deviceId);
        redisCache.deleteObject(DEVICE_LAST_ACTIVE_KEY + deviceId);

        // 从所有设备集合中移除 - 使用扩展的 RedisSetCache
        redisSetCache.removeSetValue(ALL_DEVICES_KEY, deviceId);

        log.info("移除设备 {} 的状态信息", deviceId);
    }

    /**
     * 清理过期设备状态
     */
    public void cleanupExpiredDevices(long expiryTime) {
        Set<String> deviceIds = redisCache.getCacheSet(ALL_DEVICES_KEY);
        long currentTime = System.currentTimeMillis();

        if (deviceIds != null) {
            for (String deviceId : deviceIds) {
                Long lastActive = getDeviceLastActive(deviceId);

                if (lastActive != null && currentTime - lastActive > expiryTime) {
                    removeDevice(deviceId);
                }
            }
        }
    }

    /**
     * 获取设备统计信息
     */
    public Map<String, Object> getDeviceStatistics() {
        Map<String, Boolean> allStatus = getAllDeviceStatus();
        long total = allStatus.size();
        long online = allStatus.values().stream().filter(Boolean::booleanValue).count();
        long offline = total - online;

        return Map.of(
                "total", total,
                "online", online,
                "offline", offline,
                "onlineRate", total > 0 ? (double) online / total : 0
        );
    }
}
